package com.atguigu.web;

import com.atguigu.pojo.User;
import com.atguigu.pojo.UserManager;
import com.atguigu.service.UserManagerService;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserManagerServiceImpl;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    protected void ajaxExistUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean b = userService.existsUsername(username);

        // 将boolean类型的值封装成map对象返回
        Map<String, Object> map = new HashMap<>();

        map.put("existUsername", b);

        Gson gson = new Gson();
        String s = gson.toJson(map);

        resp.getWriter().write(s);
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());
        Integer id = userService.getLoginId(username);
        user.setId(id);
        // 将用户id写入user对象中
        user.setId(userService.getLoginId(user.getUsername()));
        if (userService.Login(user)) {
            // 将用户信息保存到session域中，当前会话都有效
            req.getSession().setAttribute("user", user);
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        } else {
            // 用于显示登入失败的信息
            req.setAttribute("message", "用户名和密码错误");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        }
    }

    /**
     * 注销
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1、销毁Session中用户登录的信息（或者销毁Session）
        req.getSession().invalidate();
        // 2、重定向到首页
        resp.sendRedirect(req.getContextPath());
    }

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获得Session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        // 将表单提交的信息打包到User对象中
        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());
        // 判断用户名是否存在 不存在回传错误信息，存在保存至数据库
        if (userService.registUser(user) && req.getParameter("code").equalsIgnoreCase(token)) {
            req.getSession().setAttribute("user", user);
            req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
        } else {
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }

    protected void login_manager(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 如果之前登陆过，在当前会话中，不必重新登录了
        if (req.getSession().getAttribute("userManager") != null) {
            req.getRequestDispatcher("/pages/manager/manager.jsp").forward(req, resp);
        } else {
            // 获得请求参数，并封装成一个UserManager对象
            UserManager userManager = WebUtils.copyParamToBean(req.getParameterMap(), new UserManager());
            UserManagerService userManagerService = new UserManagerServiceImpl();
            if (userManagerService.Login(userManager)) {
                // 将用户信息保存到session域中，当前会话都有效
                req.getSession().setAttribute("userManager", userManager);
                req.getRequestDispatcher("/pages/manager/manager.jsp").forward(req, resp);
            } else {
                // 用于显示登入失败的信息
                req.setAttribute("message", "用户名和密码错误");
                req.getRequestDispatcher("/pages/user/login_manager.jsp").forward(req, resp);
            }
        }
    }

}
